#include "demo.h"

int get_apid(const char *ap, vector_t *g)
{
	int J;
	iterator_t iv;
	struct vertex v;
	//printf("	%s", ap);
	for(iv = vector_begin(g), J = 0; !iterator_equal(iv, vector_end(g)); iv = iterator_next(iv), J++)
	{
		iterator_get_value(iv, &v);
		if (strcmp(ap, v.vlabel) == 0)
		{
			break;
		}
	}
	return J;
}

const char * get_apname(int num, vector_t *g)
{
	int J;
	iterator_t iv;
	struct vertex vtemp, v;
	char * ans;
	
//	printf("\n-------%d-------\n", num);
	
	for (iv = vector_begin(g), J = 0; J <= num; iv = iterator_next(iv), J++)
	{
		iterator_get_value(iv, &v);
		strcpy(ans, v.vid);
	}
	
	return ans;
}

void printMatrix(vector_t *g)
{
	int J, Q, K;
	int start, end;
	iterator_t iv, ie, itmp;
	struct vertex v, vtmp;
	struct edge e;
	printf("draw a map:\n	");
	for(iv = vector_begin(g); !iterator_equal(iv, vector_end(g)); iv = iterator_next(iv))
	{
		iterator_get_value(iv, &v);
		printf("%s	", v.vlabel);
	}
	printf("\n");
	
	for(iv = vector_begin(g), start = 0; !iterator_equal(iv, vector_end(g)); iv = iterator_next(iv), start++)
	{
		iterator_get_value(iv, &v);
		//printf("%s", v.vlabel);
		for (ie = vector_begin(v.edges); !iterator_equal(ie, vector_end(v.edges)); ie = iterator_next(ie))
		{
			iterator_get_value(ie, &e);
			end = get_apid(e.elabel, g);
			//printf("	%d", end);
			matrix[start][end] = e.time;
		}
		//printf("\n");
	}
	
	for(iv = vector_begin(g), start = 0; !iterator_equal(iv, vector_end(g)); iv = iterator_next(iv), start++)
	{
		iterator_get_value(iv, &v);
		printf("%s", v.vlabel);
		for (ie = vector_begin(g), end = 0; !iterator_equal(ie, vector_end(g)); ie = iterator_next(ie), end++)
		{
			printf("	%d", matrix[start][end]);
		}
		printf("\n");
	}
}

int multiply(vector_t *g)
{
	iterator_t iv_1, iv_2, iv_3;	
	int i, j, k, flag = 0;
	printf("-");

	memcpy(m_tmp, matrix2, sizeof(m_tmp));
	for(iv_1 = vector_begin(g), i = 1; !iterator_equal(iv_1, vector_end(g)); iv_1 = iterator_next(iv_1), i++)
	for(iv_2 = vector_begin(g), j = 1; !iterator_equal(iv_2, vector_end(g)); iv_2 = iterator_next(iv_2), j++)
	{
		if(i == j || matrix2[i][j] > 0) continue;
		for(iv_3 = vector_begin(g), k = 1; !iterator_equal(iv_3, vector_end(g)); iv_3 = iterator_next(iv_3), ++k)
		{
			if(matrix2[i][k] > 0 && matrix[k][j] > 0)
			{
				int t;
				flag = 1;
				t = matrix2[i][k] + matrix2[k][j];
				if(m_tmp[i][j] == 0 || m_tmp[i][j] > t)
				{
					memcpy(&paths[i][j][0], &paths[i][k][0], sizeof(int)*AP_COUNT);
					paths[i][j][++paths[i][j][0]] = k;
					m_tmp[i][j] = t;
				}	
			}
		}
	}
	memcpy(matrix2, m_tmp, sizeof(m_tmp));
	return flag;
}

//computing matrix
int matrix_power(vector_t *g)
{
	int k;
	memset(paths, 0, sizeof(paths));
	memcpy(matrix2, matrix, sizeof(matrix));
	for(k=1; k < Number_sites && multiply(g); ++k);
	printf("\nComplete %d to the power. \n", k-1);
	return k;
}